package com.jieli.bt.att.util

import android.content.Context
import android.os.Build
import android.view.Gravity
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.google.android.material.snackbar.BaseTransientBottomBar.Duration
import com.jieli.bt.att.R

/**
 * ToastUtil
 * @author zqjasonZhong
 * @since 2024/5/21
 * @email zhongzhuocheng@zh-jieli.com
 * @desc 提示框工具类
 */
object ToastUtil {

    private var toast: Toast? = null

    fun showTips(
        context: Context,
        content: String,
        @Duration duration: Int = Toast.LENGTH_LONG,
        resID: Int = 0
    ) {
        abortShowTips()
        Toast.makeText(context, content, duration).also {
            toast = it
            if (resID != 0) {
                context.getView(R.layout.view_custom_toast).also { view ->
                    it.view = view
                    view.findViewById<TextView>(R.id.tv_message).text = content
                    view.findViewById<ImageView>(R.id.iv_result).setImageResource(resID)
                }
            }
            it.setGravity(Gravity.CENTER, 0, 0)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                it.addCallback(object : Toast.Callback() {
                    override fun onToastHidden() {
                        toast = null
                    }
                })
            }
            it.show()
        }
    }

    fun success(context: Context, content: String) {
        showTips(context, content, resID = R.drawable.ic_check_green)
    }

    fun error(context: Context, content: String){
        showTips(context, content, resID = R.drawable.ic_failure_red)
    }

    private fun abortShowTips() {
        toast?.cancel()
        toast = null
    }

}